<!-- 个人信息 -->
<template>
  <div class="profile-page">
    <div class="page-header">
      <h2 class="page-title">个人信息</h2>
      <button class="btn-danger" @click="logout">退出登录</button>
    </div>
    <div class="card">
      <div class="form-grid">
        <div class="form-item"><label>员工编号</label><input disabled :value="profile.employeeNo"></div>
        <div class="form-item"><label>员工账号</label><input disabled :value="profile.account"></div>
        <div class="form-item"><label>员工姓名</label><input disabled :value="profile.name"></div>
        <div class="form-item"><label>手机</label><input disabled :value="profile.phone"><a class="link" @click="openChangePhone">更换</a></div>
        <div class="form-item"><label>班组</label><input disabled :value="profile.team"></div>
        <div class="form-item"><label>角色</label><input disabled :value="profile.role"></div>
        <div class="form-item"><label>入职时间</label><input disabled :value="profile.entryDate"></div>
        <div class="form-item full"><label>备注</label><input disabled :value="profile.remark"></div>
      </div>
    </div>

    <div class="card">
      <h3 class="card-title">第三方账号绑定</h3>
      <div class="bind-grid">
        <div class="bind-item">
          <div class="avatar"></div>
          <div class="bind-info">
            <div class="bind-name">微信</div>
            <div class="bind-desc">昵称：产品大G</div>
          </div>
          <button class="btn-secondary">解绑</button>
        </div>
        <div class="bind-item">
          <div class="avatar"></div>
          <div class="bind-info">
            <div class="bind-name">钉钉</div>
            <div class="bind-desc">未绑定</div>
          </div>
          <button class="btn-primary">绑定</button>
        </div>
      </div>
    </div>

  </div>
  <!-- 修改手机号对话框 -->
  <el-dialog v-model="changePhoneVisible" title="更换手机号" width="460px" append-to-body>
    <div v-if="changeStep===1" class="cp-step">
      <div class="form-row" style="display:flex; gap:10px; align-items:center;">
        <el-input v-model="oldPhone" placeholder="请输入当前手机号（手动输入）" />
      </div>
      <div class="form-row" style="display:flex; gap:10px; align-items:center; margin-top:8px;">
        <el-input v-model="oldCode" placeholder="验证码" />
        <el-button :disabled="oldCountdown>0" @click="sendOldCode">{{ oldCountdown>0 ? oldCountdown+'s' : '获取验证码' }}</el-button>
      </div>
      <div style="margin-top:12px; text-align:right;">
        <el-button @click="changePhoneVisible=false">取 消</el-button>
        <el-button type="primary" :loading="changeLoading" @click="verifyOldPhone">下一步</el-button>
      </div>
    </div>
    <div v-else class="cp-step">
      <div class="form-row" style="display:flex; gap:10px; align-items:center;">
        <el-input v-model="newPhone" placeholder="新手机号" />
      </div>
      <div class="form-row" style="display:flex; gap:10px; align-items:center; margin-top:8px;">
        <el-input v-model="newCode" placeholder="验证码" />
        <el-button :disabled="newCountdown>0" @click="sendNewCode">{{ newCountdown>0 ? newCountdown+'s' : '获取验证码' }}</el-button>
      </div>
      <div style="margin-top:12px; text-align:right;">
        <el-button @click="changePhoneVisible=false">取 消</el-button>
        <el-button type="primary" :loading="changeLoading" @click="submitNewPhone">完成</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { ElMessage } from 'element-plus'
import http from '@/api/http'
import { clearToken, getToken } from '@/api/http'
export default {
  name: 'Profile',
  data() {
    return {
      // 顶部展示用视图模型
      profile: {
        employeeNo: '',
        account: '',
        name: '',
        phone: '',
        team: '',
        role: '',
        entryDate: '',
        remark: '-',
      },
      userId: '',
      userInfo: null,
      infoLoading: false,
      // 修改手机号对话框
      changePhoneVisible: false,
      changeStep: 1, // 1 验证旧手机; 2 绑定新手机
      oldPhone: '',
      oldCode: '',
      oldCountdown: 0,
      oldTimer: null,
      newPhone: '',
      newCode: '',
      newCountdown: 0,
      newTimer: null,
      changeLoading: false,
      UPDATE_PHONE_URL: '/intelligent-login/login/updatePhone', // 根据后端实际接口修改
      PHONE_REGEX: /^1[3-9]\d{9}$/,
      maskPhone: (p) => p ? (String(p).replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')) : '',
      // 字段中文名映射（可按需扩充）
      labelMap: {
        userCode: '员工编号',
        username: '用户名',
        realName: '姓名',
        phone: '手机号',
        email: '邮箱',
        roleName: '角色',
        deptName: '部门',
        hireDate: '入职时间',
        createTime: '创建时间',
        remark: '备注',
        status: '状态',
        deptId: '部门ID',
      }
    }
  },
  computed: {
    filteredInfo() {
      if (!this.userInfo || typeof this.userInfo !== 'object') return {}
      const exclude = new Set(['id', 'userId', 'salt'])
      const out = {}
      Object.keys(this.userInfo).forEach(k => {
        if (!exclude.has(k)) out[k] = this.userInfo[k]
      })
      return out
    }
  },
  methods: {
    async logout() {
      try {
        clearToken()
        localStorage.removeItem('userInfo')
        sessionStorage.removeItem('userInfo')
        localStorage.removeItem('permissions')
        sessionStorage.removeItem('permissions')
        ElMessage.success('已退出登录')
        this.$router.replace('/login')
      } catch (e) {
        ElMessage.error(e?.message || '退出登录失败')
      }
    },
    // —— 修改手机号：UI ——
    openChangePhone() {
      this.changePhoneVisible = true
      this.changeStep = 1
      this.oldPhone = this.profile.phone || '' // 预填可编辑
      this.oldCode = ''
      this.newPhone = ''
      this.newCode = ''
      this.oldCountdown = 0
      this.newCountdown = 0
      if (this.oldTimer) clearInterval(this.oldTimer)
      if (this.newTimer) clearInterval(this.newTimer)
    },
    // —— 修改手机号：校验旧手机验证码 ——
    async verifyOldPhone() {
      const phone = (this.oldPhone || '').trim()
      const code = (this.oldCode || '').trim()
      if (!this.PHONE_REGEX.test(phone)) return ElMessage.error('当前手机号格式不正确')
      if (!code) return ElMessage.error('请输入验证码')
      this.changeLoading = true
      try {
        const res = await http.post('/intelligent-login/login/phoneLogin', { phone, code }, { showError: false })
        const b = res?.data || {}
        const ok = b?.success === true || b?.code === 0 || b?.code === 200
        if (!ok) throw new Error(b?.message || b?.msg || '验证失败，请重试')
        this.changeStep = 2
        ElMessage.success('已验证当前手机号')
      } catch (e) {
        ElMessage.error(e?.response?.data?.message || e.message || '验证失败')
      } finally {
        this.changeLoading = false
      }
    },
    // —— 修改手机号：发送验证码（旧）——
    async sendOldCode() {
      const phone = (this.oldPhone || '').trim()
      if (!this.PHONE_REGEX.test(phone)) return ElMessage.error('当前手机号格式不正确')
      if (this.oldCountdown > 0) return
      try {
        const res = await http.post('/intelligent-login/login/send-code', { phone }, { showError: false })
        const b = res?.data || {}
        const ok = b?.success === true || b?.code === 0 || b?.code === 200
        const msg = b?.message || b?.msg || '验证码已发送'
        if (!ok) throw new Error(msg)
        ElMessage.success(msg)
        this.oldCountdown = 60
        this.oldTimer = setInterval(() => {
          this.oldCountdown--
          if (this.oldCountdown <= 0) {
            this.oldCountdown = 0
            clearInterval(this.oldTimer)
          }
        }, 1000)
      } catch (e) {
        ElMessage.error(e?.response?.data?.message || e.message || '发送失败')
      }
    },
    // —— 修改手机号：发送验证码（新）——
    async sendNewCode() {
      const phone = (this.newPhone || '').trim()
      if (!this.PHONE_REGEX.test(phone)) return ElMessage.error('请输入新手机号')
      if (this.newCountdown > 0) return
      try {
        const res = await http.post('/intelligent-login/login/send-code', { phone }, { showError: false })
        const b = res?.data || {}
        const ok = b?.success === true || b?.code === 0 || b?.code === 200
        const msg = b?.message || b?.msg || '验证码已发送'
        if (!ok) throw new Error(msg)
        ElMessage.success(msg)
        this.newCountdown = 60
        this.newTimer = setInterval(() => {
          this.newCountdown--
          if (this.newCountdown <= 0) clearInterval(this.newTimer)
        }, 1000)
      } catch (e) {
        ElMessage.error(e?.response?.data?.message || e.message || '发送失败')
      }
    },
    // —— 修改手机号：提交绑定新手机 ——
    async submitNewPhone() {
      const phone = (this.newPhone || '').trim()
      const code = (this.newCode || '').trim()
      if (!this.PHONE_REGEX.test(phone)) return ElMessage.error('请输入新手机号')
      if (!code) return ElMessage.error('请输入验证码')
      this.changeLoading = true
      try {
        // 直接调用后端更新手机号接口（后端会同时校验验证码）
        const u = await http.post(this.UPDATE_PHONE_URL, { phone, code }, { showError: false })
        const ub = u?.data || {}
        const uok = ub?.success === true || ub?.code === 0 || ub?.code === 200
        if (!uok) throw new Error(ub?.message || ub?.msg || '手机号修改失败')

        // 更新本地展示
        this.profile.phone = phone
        ElMessage.success('手机号已更新')
        this.changePhoneVisible = false
      } catch (e) {
        ElMessage.error(e?.response?.data?.message || e.message || '修改失败')
      } finally {
        this.changeLoading = false
      }
    },
    mapUserInfoToProfile(u) {
      if (!u) {
        this.profile = { employeeNo: '', account: '', name: '', phone: '', team: '', role: '', entryDate: '', remark: '-' }
        return
      }
      // 根据后端字段进行灵活映射并兜底
      this.profile.employeeNo = String(u.employeeNo || u.empNo || u.jobNo || u.userCode || '—').replace(/_/g, '')
      this.profile.account = u.account || u.username || u.email || '—'
      this.profile.name = u.name || u.realName || u.nickname || '—'
      this.profile.phone = u.phone || u.mobile || '—'
      this.profile.team = u.team || u.groupName || u.deptName || '—'
      this.profile.role = Array.isArray(u.roles) ? u.roles.join(',') : (u.roleName || u.role || '—')
      this.profile.entryDate = u.entryDate || u.hireDate || u.createdAt || u.createTime || '—'
      this.profile.remark = u.remark || u.memo || '-'
    },
    async fetchUserInfo() {
      const id = (this.userId || '').trim()
      if (!id) return ElMessage.warning('请输入用户ID')
      this.infoLoading = true
      try {
        const res = await http.get('/intelligent-login/user', { params: { id }, showError: false })
        const body = res?.data || {}
        const ok = body?.success === true || body?.code === 0 || body?.code === 200 || body?.data
        if (!ok) throw new Error(body?.message || body?.msg || '查询失败')
        this.userInfo = body?.data || body
        this.mapUserInfoToProfile(this.userInfo)
      } catch (e) {
        this.userInfo = null
        this.mapUserInfoToProfile(null)
        ElMessage.error(e?.response?.data?.message || e.message || '查询失败')
      } finally {
        this.infoLoading = false
      }
    },
    formatValue(val) {
      if (val === null || val === undefined || val === '') return '-'
      if (Array.isArray(val)) return val.join(', ')
      if (typeof val === 'object') return JSON.stringify(val)
      return String(val)
    },
    base64UrlDecode(str) {
      try {
        // JWT payload is base64url encoded
        const pad = (s) => s + '==='.slice((s.length + 3) % 4)
        const b64 = pad(str.replace(/-/g, '+').replace(/_/g, '/'))
        return decodeURIComponent(Array.prototype.map.call(atob(b64), c =>
            '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
        ).join(''))
      } catch (_) { return '' }
    },
    parseJwt(token) {
      try {
        const parts = (token || '').split('.')
        if (parts.length < 2) return null
        const json = this.base64UrlDecode(parts[1])
        return JSON.parse(json)
      } catch (_) { return null }
    },
    initUserIdFromToken() {
      const token = getToken()
      const payload = this.parseJwt(token)
      const id = payload?.userId || payload?.id || payload?.uid || payload?.sub
      if (id != null && id !== '') {
        this.userId = String(id)
      }
    },
  },
  mounted() {
    // 从 token 解析用户ID并自动查询
    this.initUserIdFromToken()
    if (this.userId) {
      this.fetchUserInfo()
    }
  },
  beforeUnmount() {
    if (this.oldTimer) clearInterval(this.oldTimer)
    if (this.newTimer) clearInterval(this.newTimer)
  }
}
</script>

<style scoped>
.profile-page { padding: 20px; background: #f5f7fa; }
.page-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
.page-title { margin: 0; font-size: 20px; font-weight: bold; }
.card { background: #fff; border-radius: 8px; padding: 16px; margin-bottom: 16px; }
.card-title { margin: 0 0 12px; font-size: 16px; }
.form-grid { display: grid; grid-template-columns: repeat(2, minmax(260px, 420px)); gap: 12px 24px; }
.form-item { display: flex; align-items: center; gap: 10px; }
.form-item.full { grid-column: 1 / -1; }
.form-item label { width: 90px; color: #606266; }
.form-item input { flex: 1; padding: 8px 10px; border: 1px solid #dcdfe6; border-radius: 4px; background: #f5f7fa; }
.form-item .link { margin-left: 8px; color: #409eff; cursor: pointer; }
.bind-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; }
.bind-item { display: flex; align-items: center; gap: 16px; border: 1px solid #ebeef5; border-radius: 8px; padding: 16px; }
.avatar { width: 48px; height: 48px; border-radius: 6px; background: #d8dee9; }
.bind-info { flex: 1; }
.bind-name { font-weight: 600; margin-bottom: 4px; }
.bind-desc { color: #909399; font-size: 12px; }
.btn-primary { background: #409eff; color: #fff; border: none; padding: 6px 14px; border-radius: 4px; cursor: pointer; }
.btn-secondary { background: #fff; color: #606266; border: 1px solid #dcdfe6; padding: 6px 14px; border-radius: 4px; cursor: pointer; }
.btn-danger { background: #e53e3e; color: #fff; border: none; padding: 6px 14px; border-radius: 4px; cursor: pointer; }
.btn-danger:hover { background: #c53030; }
</style>
